<template>
  <div class="slider-validate">
    <div class="bgc"></div>
    <div class="text" onselectstart="return false;">{{ text }}</div>
    <div class="bar" v-drag>
      &gt;&gt;
    </div>
  </div>
</template>
<script>
export default {
  name: 'sliderValidate',
  data() {
    return {
      text: '请拖动滑块解锁',
      success: false
    };
  },
  directives: {
    drag: {
      inserted(el, binding, vnode) {
        el.onmousedown = function(e) {
          let vm = vnode.context;
          let bg = el.previousSibling.previousSibling;
          var disx = e.pageX - el.offsetLeft;
          var withPN = el.parentNode.clientWidth;
          el.style.transition = '';
          bg.style.transition = '';
          document.onmousemove = function(e) {
            el.style.left = e.pageX - disx + 'px';
            bg.style.width = e.pageX - disx + 'px';
            if (el.offsetLeft >= withPN - el.clientWidth) {
              el.style.left = withPN - el.clientWidth + 'px';
              bg.style.width = withPN - el.clientWidth + 'px';
              el.innerHTML = '&radic;';
              vm.text = '验证通过';
              vm.success = true;
              bg.style.backgroundColor = 'lightgreen';
              el.onmousedown = null;
              document.onmousemove = null;
              setTimeout(() => {
                vm.$emit('onSuccess');
              }, 1000);
              return;
            } else if (el.offsetLeft < 0) {
              el.style.left = 0;
              bg.style.width = 0;
              return;
            }
          };
          document.onmouseup = function() {
            if (vm.success) {
              return;
            } else {
              el.style.left = 0;
              bg.style.width = 0;
              el.style.transition = 'left 1s ease';
              bg.style.transition = 'width 1s ease';
              vm.$emit('error');
            }
            document.onmousemove = document.onmouseup = null;
          };
        };
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.slider-validate {
  position: relative;
  width: 400px;
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  background-color: #e8e8e8;
  .bgc {
    width: 30px;
    height: 100%;
    background: skyblue;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    user-select: none;
  }
  .text {
    position: absolute;
    width: 100%;
    height: 100%;
    text-align: center;
    user-select: none;
    top: 0;
    left: 0;
  }
  .bar {
    position: absolute;
    top: 0;
    left: 0;
    width: 30px;
    height: 100%;
    border: 1px solid #ccc;
    cursor: move;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666;
    user-select: none;
    background-color: #fff;
    box-sizing: border-box;
  }
}
</style>
